import React from 'react';
import { Button } from 'antd'

class HanWang extends React.Component {

  constructor(props) {
    super(props);
    this.ws = "";
    this.bConnectWS = false;
    this.bClosed = false;
    this.index = 0;
    this.state = {
      disabled: false
    }
  }

  sendWsMessage(msg) {
    this.ws.send(JSON.stringify(msg));
  }

  componentDidMount() {
    let url = "ws://localhost:7896";
    if('WebSocket' in window) {
      this.ws = new WebSocket(url);
    } else if('MozWebSocket' in window) {
      this.ws = new MozWebSocket(url);
    } else {
      this.setState({ disabled: true });
    }
    if(this.ws) {
      this.ws.onopen = () => {
        this.bConnectWS = true;
        this.sendWsMessage({ FuncName: 'InitCamLib' });
        this.bClosed = false;
      };
      this.ws.onerror = () => {
        this.setState({ disabled: true });
      };
      this.ws.onmessage = e => {
        if(typeof(e.data) === 'string') {
          let str = e.data;
          if(str.indexOf('FuncName') > -1) {
            let data = JSON.parse(str);
            if(data.FuncName === 'InitCamLib') {
              this.sendWsMessage({ FuncName: 'StartPreview', index: this.index });
            }
          }
          if(str.indexOf('@Cap2Base64@') > -1) {
            let base64 = str.split('@Cap2Base64@')[1];
            this.props.onCapture(base64);
          }
        }
      };
      this.ws.onclose = () => {
        this.bConnectWS = false;
        this.setState({ disabled: true });
      }
    }
  }

  componentWillUnmount() {
    if(this.bClosed)
      return;
    if(this.bConnectWS) {
      clearInterval();
      this.sendWsMessage({ FuncName: 'StopPreview', index: this.index });
      this.sendWsMessage({ FuncName: 'UnInitCamLib' });
      this.ws.close();
    }
  }

  capture = () => {
    this.sendWsMessage({ FuncName: 'Cap2Base64', index: this.index });
  };

  render() {
    const { children, buttonProps } = this.props;
    const { disabled } = this.state;
    return (
      <Button
        disabled={disabled}
        onClick={this.capture}
        {...buttonProps}
      >
        {children}
      </Button>
    );
  }
}

HanWang.propTypes = {
  onCapture: React.PropTypes.func
};

export default HanWang;
